package com.yonyou.pmclouds.billview.plugin;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.SuperVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import com.yonyou.pmclouds.businessobject.util.BusinessObjectConsts;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.workflow.service.rmiitf.IWorkFlowService;
import com.yonyou.pmclouds.workstopreport.entity.WorkStopVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class WorkStopPlugin implements IBillViewCustomPlugin {

    @Autowired
    private UserInfoQuery userInfoQuery;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectSimpleQuery projectSimpleQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private OrganizationQuery organizationQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private IWorkFlowService iworkFlowService;

    @Override
    public Object[] fillListBuziField(Object[] objects) throws BusinessException {
        if (null == objects || objects.length == 0) {
            return new Object[0];
        }
        //遍历结果集
        WorkStopVO[] workStopVOS = new WorkStopVO[objects.length];
        for (int i = 0; i < objects.length; i++) {
            workStopVOS[i] = (WorkStopVO) objects[i];
        }
        //获取结果集所有项目id
        List<String> pkPorjects = Arrays.stream(workStopVOS).map(WorkStopVO::getPkProject).collect(Collectors.toList());
        //获取所有项目以及项目VO
        Map<String, ProjectVO> projectMap = projectSimpleQuery.queryProjects(pkPorjects.toArray(new String[0]));
        //根据项目信息获取组织信息
        Map<String, OrganizationVO> pkSrcToOrg = pkSrcToOrgByProject(projectMap);
        //补充组织信息
        fillOrgInfo(workStopVOS, projectMap, pkSrcToOrg);
        //补充项目信息
        fillProjectInfo(workStopVOS, projectMap);
        //补充创建者姓名
        fillCreatorName(objects);

        return objects;
    }

    @Override
    public Map<String, Object[]> fillDetailBuziField(SuperVO superVO, HttpServletRequest request) throws BusinessException {
        Map<String, Object[]> resultMap = new HashMap<String, Object[]>();
        resultMap.put(BusinessObjectConsts.PM_WORKSTOP, new Object[]{superVO});
        return resultMap;
    }

    @Override
    public String getBillType() {
        return BillTypeConst.WORKSTOP_BILLTYPE;
    }

    /**
     * 根据项目中的pkOrg获取组织VO
     * @param projectMap
     * @return
     * @throws BusinessException
     */
    private Map<String, OrganizationVO> pkSrcToOrgByProject(Map<String, ProjectVO> projectMap) throws BusinessException {
        Map<String, OrganizationVO> pkSrcToOrg = new HashMap<String, OrganizationVO>();
        if (projectMap != null && projectMap.size() > 0) {
            List<String> pkOrgs = projectMap.values().stream().map(ProjectVO::getPkOrg).filter(vo -> StringUtils.isNotEmpty(vo)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(pkOrgs)) {
                OrganizationVO[] organizationVOs = organizationQuery.queryByPkSrcs(RuntimeEnvironment.getTenantId(), pkOrgs.toArray(new String[0]));
                pkSrcToOrg = Arrays.stream(organizationVOs).filter(organizationVO -> StringUtils.isNotEmpty(organizationVO.getPkSrc())).collect(Collectors.toMap(OrganizationVO::getPkSrc, organizationVO -> organizationVO));
            }
        }
        return pkSrcToOrg;
    }

    /**
     * 填充创建者信息
     * @param objects
     */
    private void fillCreatorName(Object[] objects) {
        userInfoQuery.tranUserInfoField(objects, new String[]{CommonFieldConst.CREATOR}, new String[]{CommonFieldConst.CREATOR_NAME});
    }

    /**
     * 填充项目信息
     * @param workStopVOS
     * @param projectMap
     */
    private void fillProjectInfo(WorkStopVO[] workStopVOS, Map<String, ProjectVO> projectMap) {
        for (WorkStopVO workStopVO : workStopVOS){
            //获取项目信息
            ProjectVO projectVO = projectMap.get(workStopVO.getPkProject());
            if(projectVO != null){
                //赋值项目名以及项目编号
                workStopVO.setProjectName(projectVO.getSname());
                workStopVO.setProjectCode(projectVO.getScode());
            }
        }
    }

    /**
     * 填充组织信息
     *
     * @param workStopVOS
     * @param projectMap
     * @param pkSrcToOrg
     * @throws BusinessException
     */
    private void fillOrgInfo(WorkStopVO[] workStopVOS, Map<String, ProjectVO> projectMap, Map<String, OrganizationVO> pkSrcToOrg) throws BusinessException {
        String loginUserId = RuntimeEnvironment.getLoginUserId();
        for (WorkStopVO workStopVO : workStopVOS) {
            //获取项目信息
            ProjectVO projectVO = projectMap.get(workStopVO.getPkProject());
            if (projectVO != null) {
                //赋值项目名以及项目编号
                workStopVO.setProjectName(projectVO.getSname());
                workStopVO.setProjectCode(projectVO.getScode());
            }
            workStopVO.setCanApprove(false);
            boolean b = iworkFlowService.checkApprovePerm(workStopVO.getPkWorkstopreport(), loginUserId);
            if (b) {
                workStopVO.setCanApprove(true);
            }
            if (pkSrcToOrg.get(projectVO.getPkOrg()) != null) {
                OrganizationVO organizationVO = pkSrcToOrg.get(projectVO.getPkOrg());
                workStopVO.setOrgName(organizationVO.getSname());
            }
        }
    }
}
